'''
Created on  6. 3 . 2020
@author: 晨遇韬
@version: V.2.0.0
@Descriptions:
增加串口通信与CRC校验
'''
#数据发送更新
def dataSandUpdate(x, y):
    temp = struct.pack("<bbii",                #格式为2个字符2个整型
                   0xAA,                       #帧头1
                   0xAE,                       #帧头2
                   int(x), # up sample by 4    #数据1
                   int(y)) # up sample by 4    #数据2
    uart.write(temp)
#数据接收更新
def dataReciveUpdate():
    if uart.any() :
        while (uart.readchar() == 0x3f):
            for i in range(10):
                b = uart.readchar()
                c.append(b)
            print(c)
            c=[0]
            DI = 0x07
            crc8_table = []
#添加CRC8校验
def init_crc8():
    for i in range(256):
        crc = i
        for j in range(8):
            tmp = crc & 0x80
            if tmp:
                crc = (crc << 1)^DI
            else:
                crc = (crc << 1)^0
        crc8_table.append(crc & 0xFF)
#检验CRC8校验
def crc8(buf, n):
    crc_r = 0
    if not(len(crc8_table)):
        init_crc8()

    for i in range(n):
        crc_r = crc8_table[crc_r ^ buf[i]]
        crc_r &= 0xFF
    crc = hex(~crc_r & 0xff)
    return crc
#CRC8测试程序
def TestCrc8():
    data = "A5 D1 08 01 00 04 08 03 01 23 23 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
    data = data.replace(" ","")
    SendData = unhexlify(bytes(data,"UTF-8"))
    crc = crc8(SendData, len(SendData))
    data += crc[2:] + "5A"
    SendData = unhexlify(bytes(data,"UTF-8"))
    print(SendData)




